package action;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringBufferInputStream;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import server.GetRadomValue;
import service.tUserService;
import entity.tUser;

public class LoginAction {
	private String username;
	private String pwd;
	private tUserService tuserService;
	private InputStream isSameStream;
	public String login() throws IOException {
		
		ServletResponse response = ServletActionContext.getResponse();
		HttpSession session = ServletActionContext.getRequest().getSession();
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		GetRadomValue.getInstance().setIfUse(false);
		tUser tuser=new tUser();
		tuser.setPwd(pwd);
		tuser.setUserName(username);
		tUser user = tuserService.login(tuser);
		if (user != null) {
			session.setAttribute("user", user);
			out.print("yes");
			return "success";
		} else {
			out.print("no");
			return "error";
		}
	}
	public String loginCheck() throws Exception {
		// 后台验证当same=0的时候返回给struts，导致ajax收到请求返回错误信息
		// 反之same=1则成功的进入主页面
		String same = "0";
		if (pwd != null) {
			tUser tuser=new tUser();
			tuser.setPwd(pwd);
			tuser.setUserName(username);
			tUser user = tuserService.login(tuser);// 这要加密

			// 返回user是否为空
			if (user != null) {
				same = "1";// 表示密码正确
			}
		}
		this.setIsSameStream(new StringBufferInputStream(same));

		// 返回结果单词
		return "success";

	}

	public String exit(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		session.invalidate();
		return "login";
	} 
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public tUserService getTuserService() {
		return tuserService;
	}
	public void setTuserService(tUserService tuserService) {
		this.tuserService = tuserService;
	}
	public InputStream getIsSameStream() {
		return isSameStream;
	}
	public void setIsSameStream(InputStream isSameStream) {
		this.isSameStream = isSameStream;
	}
	
	
	
	
}
